package com.yilin.tms.system.controller;

import com.baomidou.mybatisplus.annotation.TableField;
import com.yilin.commons.util.StringUtil;
import com.yilin.tms.core.application.AppUtil;
import com.yilin.tms.core.application.PageData;
import com.yilin.tms.core.application.ReturnData;
import com.yilin.tms.core.commons.base.BaseController;
import com.yilin.tms.core.commons.annotation.NotNull;
import com.yilin.tms.core.commons.annotation.SkipLoginVerify;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.entity.system.system.AppVersion;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.entity.user.hatch.HatchPlatProduct;
import com.yilin.tms.core.remote.IUserRemote;
import com.yilin.tms.system.service.IAppVersionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.persistence.Transient;
import java.util.Date;

@RestController
@RequestMapping("/system/app/")
public class AppVersionController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(AppVersionController.class);

    @Resource
    private IAppVersionService resourceService;
    @Resource
    private IUserRemote userRemote;

    /**
     * 功能描述 前端获取app真实路径 下载路径
     */
    @RequestMapping(value = "downloadAppUrl")
    @NotNull({"appType", "softwareType"})
    @SkipLoginVerify
    public String downloadAppUrl(AppVersion.AppType appType,  AppVersion.SoftwareType softwareType,String platId, String productCode) {
        if (platId == null) {
            HatchPlatProduct hatch = ParamUtil.isSuccess(userRemote.getPlatProductHatchByCode(productCode));
            platId = hatch.getPlatId();
        }
        AppVersion newAppVersion = resourceService.getNewAppVersion(appType,softwareType, platId, null);
        ParamUtil.isNull(newAppVersion, "此平台暂无APP,请先添加APP");
        return "redirect:"+newAppVersion.getDownloadUrl();
    }

    /**
     * 获取APP最新版本
     */
    @PostMapping(value = "getAppNewVersion")
    @SkipLoginVerify
    @NotNull({"softwareType", "appType"})
    public ReturnData<AppVersion> getAppNewVersion(AppVersion.AppType appType, AppVersion.SoftwareType softwareType, String platId, String productCode) {
        logger.info("-----------------------------------------------");
        logger.info("收到版本更新请求：appType:"+appType.name+",softwareType:"+softwareType.name+",productCode:"+productCode);
        if (platId == null) {
            HatchPlatProduct hatch = ParamUtil.isSuccess(userRemote.getPlatProductHatchByCode(productCode));
            platId = hatch.getPlatId();
        }
        AppVersion newAppVersion = resourceService.getNewAppVersion(appType, softwareType, platId, null);
        if (newAppVersion==null) logger.info("newAppVersion:版本为空");
        else logger.info("newAppVersion:"+newAppVersion.getVersionName());
        logger.info("-----------------------------------------------");
        if (newAppVersion!=null){
            //旧版本支持
            newAppVersion.setPath(newAppVersion.getDownloadUrl());
            newAppVersion.setSize(newAppVersion.getmSize());
            newAppVersion.setForceUpdate(newAppVersion.getmForce());
        }
        return jsonView(true, "获取APP最新版本成功", newAppVersion);
    }

    /**
     * app上传列表
     */
    @PostMapping(value = "getAPPLoadPage")
    @NotNull({"page", "limit"})
    public ReturnData<Object> getAPPLoadPage(Integer page, Integer limit, AppVersion appVersion) {
        PageData<AppVersion> appLoadPage = resourceService.getAPPLoadPage(page, limit, appVersion);
        return jsonView(SUCCESS_CODE, "获取成功", appLoadPage);
    }

    /**
     * 添加版本
     */
    @PostMapping(value = "addAppVersion")
    @NotNull({"platId", "appType", "softwareType", "versionTitle", "versionName", "content"})
    public ReturnData<Object> addAppVersion(AppVersion appUpload) {
        String[] split = appUpload.getVersionName().split("\\.");
        if (split.length != 4) {
            return jsonView(FAIL_CODE, "版本级别错误，格式必须是20xx.xx.xx.xx", null);
        }
        for (String s : split) {
            if (!AppUtil.isNumeric(s)) {
                return jsonView(FAIL_CODE, "版本级别识别错误，格式必须是数字+小数点", null);
            }
        }
        if (Integer.parseInt(split[0]) <= 0) {
            return jsonView(FAIL_CODE, "一级版本不能为0,格式(20xx.xx.xx.xx)", null);
        }
        // 版本号
        String vc = split[0] + split[1] + split[2]+ split[3];
        if (appUpload.getVersionCode() == null) appUpload.setVersionCode(Integer.parseInt(vc));
        //相同版本进行覆盖
        AppVersion uAppVersion = resourceService.getNewAppVersion(appUpload.getAppType(), appUpload.getSoftwareType(), appUpload.getPlatId(), appUpload.getVersionCode());
        if (uAppVersion != null) appUpload.setId(uAppVersion.getId());
        if (StringUtil.isEmpty(appUpload.getContent())) {
            return jsonView(FAIL_CODE, "版本内容不能为空", null);
        }
        Account user = getLoginUser();
        HatchPlatProduct platProduct = ParamUtil.isSuccess(userRemote.getPlatProductHatch(appUpload.getPlatId()));
        if (appUpload.getAppType() == AppVersion.AppType.shipper){
            appUpload.setAppIcon(platProduct.getShipperAppIcon());
        }else {
            appUpload.setAppIcon(platProduct.getTruckerAppIcon());
        }
        appUpload.setPlatName(platProduct.getPlatName());
        appUpload.setPlatId(platProduct.getPlatId());
        appUpload.setmForce(true);
        appUpload.setCreateTime(new Date());
        appUpload.setAddUserId(user.getId());
        resourceService.addAPPLoad(appUpload);
        return jsonView(SUCCESS_CODE, true, "上传成功", null);
    }

}
